// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenhttp/httpstatus.h"

namespace zen {

HttpStatusService::HttpStatusService() : m_Log(logging::Get("status"))
{
}

HttpStatusService::~HttpStatusService()
{
}

const char*
HttpStatusService::BaseUri() const
{
	return "/status/";
}

void
HttpStatusService::RegisterHandler(std::string_view Id, IHttpStatusProvider& Provider)
{
	RwLock::ExclusiveLockScope _(m_Lock);
	m_Providers.insert_or_assign(std::string(Id), &Provider);
}

void
HttpStatusService::UnregisterHandler(std::string_view Id, IHttpStatusProvider& Provider)
{
	ZEN_UNUSED(Provider);

	RwLock::ExclusiveLockScope _(m_Lock);
	m_Providers.erase(std::string(Id));
}

void
HttpStatusService::HandleRequest(HttpServerRequest& Request)
{
	using namespace std::literals;

	std::string_view Key = Request.RelativeUri();

	switch (Request.RequestVerb())
	{
		case HttpVerb::kHead:
		case HttpVerb::kGet:
			{
				RwLock::SharedLockScope _(m_Lock);
				if (auto It = m_Providers.find(std::string{Key}); It != end(m_Providers))
				{
					return It->second->HandleStatusRequest(Request);
				}
			}

			[[fallthrough]];
		default:
			return;
	}
}

}  // namespace zen
